package config

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"

	"kwdb-import/pkg/errors"

	"gopkg.in/yaml.v3"
)

// Config 应用程序配置结构
type Config struct {
	// 顶层数据库连接配置（与嵌套 Database 同步）
	Host     string `yaml:"host" json:"host"`
	Port     int    `yaml:"port" json:"port"`
	DBName   string `yaml:"-" json:"database"`
	Username string `yaml:"username" json:"username"`
	Password string `yaml:"password" json:"password"`
	SSLMode  string `yaml:"sslmode" json:"sslmode"`

	// 嵌套数据库配置，兼容测试期待的结构与键名
	Database DatabaseConfig `yaml:"database" json:"database"`

	// 连接池配置
	MaxConnections int    `yaml:"max_connections" json:"max_connections"`
	MaxIdleConns   int    `yaml:"max_idle_conns" json:"max_idle_conns"`
	MaxLifetime    string `yaml:"max_lifetime" json:"max_lifetime"`
	ConnectTimeout string `yaml:"connect_timeout" json:"connect_timeout"`
	IdleTimeout    string `yaml:"idle_timeout" json:"idle_timeout"`

	// 导入配置
	InputFile         string        `yaml:"input_file" json:"input_file"`
	InputEncoding     string        `yaml:"input_encoding" json:"input_encoding"`
	OutputDir         string        `yaml:"output_dir" json:"output_dir"`
	BatchSize         int           `yaml:"batch_size" json:"batch_size"`
	Timeout           string        `yaml:"timeout" json:"timeout"`
	MaxRetries        int           `yaml:"max_retries" json:"max_retries"`
	RetryDelay        time.Duration `yaml:"retry_delay" json:"retry_delay"`
	ConnectionTimeout time.Duration `yaml:"connection_timeout" json:"connection_timeout"`
	QueryTimeout      time.Duration `yaml:"query_timeout" json:"query_timeout"`
	Verbose           bool          `yaml:"verbose" json:"verbose"`
	DryRun            bool          `yaml:"dry_run" json:"dry_run"`

	// 执行模式：batch 或 streaming，用于导入流程的内存占用策略
	ExecutionMode string `yaml:"execution_mode" json:"execution_mode"`

	// 事务配置
	TransactionMode          string `yaml:"transaction_mode" json:"transaction_mode"`
	StatementsPerTransaction int    `yaml:"statements_per_transaction" json:"statements_per_transaction"`
	AutoRetry                bool   `yaml:"auto_retry" json:"auto_retry"`

	// 错误处理配置
	OnError   string `yaml:"on_error" json:"on_error"`
	MaxErrors int    `yaml:"max_errors" json:"max_errors"`
	LogErrors bool   `yaml:"log_errors" json:"log_errors"`

	// 日志配置
	LogLevel  string `yaml:"log_level" json:"log_level"`
	LogFormat string `yaml:"log_format" json:"log_format"`
	LogFile   string `yaml:"log_file" json:"log_file"`

	// 转换配置（顶层，用于向后兼容）
	ConvertAutoIncrement bool              `yaml:"convert_auto_increment" json:"convert_auto_increment"`
	ConvertEnumToVarchar bool              `yaml:"convert_enum_to_varchar" json:"convert_enum_to_varchar"`
	DataTypeMapping      map[string]string `yaml:"data_type_mapping" json:"data_type_mapping"`
	// 每条 INSERT 语句允许的 VALUES 组最大数量（>0 时触发拆分）
	MaxValuesPerInsert int `yaml:"max_values_per_insert" json:"max_values_per_insert"`

	// 嵌套转换配置（支持 conversion 块）
	Conversion ConversionConfig `yaml:"conversion" json:"conversion"`

	// 性能配置
	EnableParallel    bool `yaml:"enable_parallel" json:"enable_parallel"`
	WorkerCount       int  `yaml:"worker_count" json:"worker_count"`
	ParallelBatchSize int  `yaml:"parallel_batch_size" json:"parallel_batch_size"` // 并发批次大小
	MemoryLimit       int  `yaml:"memory_limit" json:"memory_limit"`
	EnableCompression bool `yaml:"enable_compression" json:"enable_compression"`

	// 监控配置
	EnableMetrics      bool   `yaml:"enable_metrics" json:"enable_metrics"`
	MetricsPort        int    `yaml:"metrics_port" json:"metrics_port"`
	HealthCheckEnabled bool   `yaml:"health_check_enabled" json:"health_check_enabled"`
	HealthCheckPath    string `yaml:"health_check_path" json:"health_check_path"`
}

// DatabaseConfig 数据库配置结构
type DatabaseConfig struct {
	Driver string `yaml:"driver" json:"driver"`
	Host   string `yaml:"host" json:"host"`
	Port   int    `yaml:"port" json:"port"`
	// 兼容两种字段命名
	Database       string        `yaml:"database" json:"database"`
	Name           string        `yaml:"name" json:"name"`
	Username       string        `yaml:"username" json:"username"`
	User           string        `yaml:"user" json:"user"`
	Password       string        `yaml:"password" json:"password"`
	SSLMode        string        `yaml:"ssl_mode" json:"ssl_mode"`
	ConnectTimeout time.Duration `yaml:"connect_timeout" json:"connect_timeout"`
	Pool           PoolConfig    `yaml:"pool" json:"pool"`
}

// UnmarshalYAML 支持将 database 既可以是映射也可以是纯字符串（表示数据库名）
func (dc *DatabaseConfig) UnmarshalYAML(value *yaml.Node) error {
	switch value.Kind {
	case yaml.ScalarNode:
		// 纯字符串，视为数据库名
		name := strings.TrimSpace(value.Value)
		dc.Name = name
		dc.Database = name
		return nil
	case yaml.MappingNode:
		// 映射，按常规结构解码
		type alias DatabaseConfig
		var aux alias
		if err := value.Decode(&aux); err != nil {
			return err
		}
		*dc = DatabaseConfig(aux)
		return nil
	default:
		return fmt.Errorf("invalid database config format: %v", value.Kind)
	}
}

// PoolConfig 连接池配置
type PoolConfig struct {
	MaxConns          int           `yaml:"max_conns" json:"max_conns"`
	MinConns          int           `yaml:"min_conns" json:"min_conns"`
	MaxConnLifetime   time.Duration `yaml:"max_conn_lifetime" json:"max_conn_lifetime"`
	MaxConnIdleTime   time.Duration `yaml:"max_conn_idle_time" json:"max_conn_idle_time"`
	HealthCheckPeriod time.Duration `yaml:"health_check_period" json:"health_check_period"`
}

// ImportConfig 导入配置
type ImportConfig struct {
	InputFile     string `yaml:"input_file" json:"input_file"`
	InputEncoding string `yaml:"input_encoding" json:"input_encoding"`
	OutputDir     string `yaml:"output_dir" json:"output_dir"`
	BatchSize     int    `yaml:"batch_size" json:"batch_size"`
	Timeout       string `yaml:"timeout" json:"timeout"`
	MaxRetries    int    `yaml:"max_retries" json:"max_retries"`
}

// TransactionConfig 事务配置
type TransactionConfig struct {
	Mode                     string `yaml:"mode" json:"mode"`
	StatementsPerTransaction int    `yaml:"statements_per_transaction" json:"statements_per_transaction"`
	AutoRetry                bool   `yaml:"auto_retry" json:"auto_retry"`
	MaxRetries               int    `yaml:"max_retries" json:"max_retries"`
}

// ErrorHandlingConfig 错误处理配置
type ErrorHandlingConfig struct {
	OnError   string `yaml:"on_error" json:"on_error"`
	MaxErrors int    `yaml:"max_errors" json:"max_errors"`
	LogErrors bool   `yaml:"log_errors" json:"log_errors"`
}

// ConversionConfig 转换配置
type ConversionConfig struct {
	AutoIncrement      bool              `yaml:"convert_auto_increment" json:"convert_auto_increment"`
	EnumToVarchar      bool              `yaml:"convert_enum_to_varchar" json:"convert_enum_to_varchar"`
	DataTypeMapping    map[string]string `yaml:"data_type_mapping" json:"data_type_mapping"`
	RemoveMySQLOptions bool              `yaml:"remove_mysql_options" json:"remove_mysql_options"`
	// 每条 INSERT 语句允许的 VALUES 组最大数量（>0 时触发拆分）
	MaxValuesPerInsert int `yaml:"max_values_per_insert" json:"max_values_per_insert"`
}

// NewConfig 创建默认配置
func NewConfig() *Config {
	return &Config{
		// 顶层数据库默认配置
		Host:     "localhost",
		Port:     5432,
		DBName:   "postgres",
		Username: "postgres",
		SSLMode:  "disable",

		// 嵌套数据库默认配置（与顶层保持一致）
		Database: DatabaseConfig{
			Host:    "localhost",
			Port:    5432,
			Name:    "postgres",
			User:    "postgres",
			SSLMode: "disable",
		},

		// 连接池默认配置
		MaxConnections: 10,
		MaxIdleConns:   5,
		MaxLifetime:    "1h",
		ConnectTimeout: "30s",
		IdleTimeout:    "15m",

		// 导入默认配置
		InputEncoding:     "utf-8",
		BatchSize:         1000,
		Timeout:           "30s",
		MaxRetries:        3,
		RetryDelay:        1 * time.Second,
		ConnectionTimeout: 30 * time.Second,
		QueryTimeout:      30 * time.Second,
		Verbose:           false,
		DryRun:            false,
		ExecutionMode:     "batch",

		// 事务默认配置
		TransactionMode:          "batch",
		StatementsPerTransaction: 100,
		AutoRetry:                true,

		// 错误处理默认配置
		OnError:   "skip",
		MaxErrors: 100,
		LogErrors: true,

		// 日志默认配置
		LogLevel:  "info",
		LogFormat: "text",

		// 转换默认配置
		ConvertAutoIncrement: true,
		ConvertEnumToVarchar: true,
		DataTypeMapping:      nil,
		MaxValuesPerInsert:   0,

		// 性能默认配置
		EnableParallel:    false,
		WorkerCount:       4,
		ParallelBatchSize: 1,   // 每个批次100条INSERT
		MemoryLimit:       512, // MB
		EnableCompression: false,

		// 监控默认配置
		EnableMetrics:      false,
		MetricsPort:        8080,
		HealthCheckEnabled: false,
		HealthCheckPath:    "/health",
	}
}

// LoadFromFile 从文件加载配置
func LoadFromFile(filename string) (*Config, error) {
	if filename == "" {
		return nil, errors.NewValidationError("config file path cannot be empty", "filename", filename)
	}

	// 检查文件是否存在
	if _, err := os.Stat(filename); os.IsNotExist(err) {
		return nil, errors.NewValidationError(fmt.Sprintf("config file does not exist: %s", filename), "filename", filename)
	}

	// 读取文件内容
	data, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, errors.NewValidationError(fmt.Sprintf("failed to read config file: %v", err), "filename", filename)
	}

	// 新策略：先解析到空配置，再与默认配置合并，避免嵌套默认值覆盖顶层
	base := NewConfig()
	fileCfg := &Config{}

	// 根据文件扩展名选择解析方式
	ext := strings.ToLower(filepath.Ext(filename))
	switch ext {
	case ".yaml", ".yml":
		err = yaml.Unmarshal(data, fileCfg)
	case ".json":
		err = json.Unmarshal(data, fileCfg)
	default:
		// 默认尝试YAML格式
		err = yaml.Unmarshal(data, fileCfg)
		if err != nil {
			// 如果YAML失败，尝试JSON
			err = json.Unmarshal(data, fileCfg)
		}
	}

	if err != nil {
		return nil, errors.NewValidationError(fmt.Sprintf("failed to parse config file: %v", err), "filename", filename)
	}

	// 将嵌套数据库字段同步到顶层（仅填充缺失项）
	fileCfg.syncFromNested()

	// 应用环境变量覆盖到文件配置
	fileCfg.ApplyEnvironmentOverrides()

	// 合并文件配置与默认配置（文件的非零值优先）
	merged := base.Merge(fileCfg)

	// 保持顶层与嵌套一致
	merged.syncToNested()

	// 验证配置
	validator := NewConfigValidator()
	if err := validator.ValidateConfig(merged); err != nil {
		return nil, err
	}

	return merged, nil
}

// LoadConfigFromFile 兼容函数名称，调用 LoadFromFile
func LoadConfigFromFile(filename string) (*Config, error) {
	return LoadFromFile(filename)
}

// SaveToFile 保存配置到文件
func (c *Config) SaveToFile(filename string) error {
	if filename == "" {
		return errors.NewValidationError("config file path cannot be empty", "filename", filename)
	}

	// 创建目录（如果不存在）
	dir := filepath.Dir(filename)
	if err := os.MkdirAll(dir, 0755); err != nil {
		return errors.NewValidationError(fmt.Sprintf("failed to create config directory: %v", err), "directory", dir)
	}

	// 根据文件扩展名选择格式
	ext := strings.ToLower(filepath.Ext(filename))
	var data []byte
	var err error

	switch ext {
	case ".json":
		data, err = json.MarshalIndent(c, "", "  ")
	default: // 默认使用YAML
		data, err = yaml.Marshal(c)
	}

	if err != nil {
		return errors.NewValidationError(fmt.Sprintf("failed to marshal config: %v", err), "format", ext)
	}

	// 写入文件
	err = ioutil.WriteFile(filename, data, 0644)
	if err != nil {
		return errors.NewValidationError(fmt.Sprintf("failed to write config file: %v", err), "filename", filename)
	}

	return nil
}

// ApplyEnvironmentOverrides 应用环境变量覆盖
func (c *Config) ApplyEnvironmentOverrides() {
	// 数据库配置
	if host := os.Getenv("KWDB_HOST"); host != "" {
		c.Host = host
	}
	if port := os.Getenv("KWDB_PORT"); port != "" {
		if p, err := strconv.Atoi(port); err == nil {
			c.Port = p
		}
	}
	if database := os.Getenv("KWDB_DATABASE"); database != "" {
		c.DBName = database
	}
	if username := os.Getenv("KWDB_USERNAME"); username != "" {
		c.Username = username
	}
	if password := os.Getenv("KWDB_PASSWORD"); password != "" {
		c.Password = password
	}
	// 支持两种命名：KWDB_SSLMODE 与 KWDB_SSL_MODE
	if sslmode := os.Getenv("KWDB_SSLMODE"); sslmode != "" {
		c.SSLMode = sslmode
	}
	if sslmode := os.Getenv("KWDB_SSL_MODE"); sslmode != "" {
		c.SSLMode = sslmode
	}

	// 导入配置
	if inputFile := os.Getenv("KWDB_INPUT_FILE"); inputFile != "" {
		c.InputFile = inputFile
	}
	if outputDir := os.Getenv("KWDB_OUTPUT_DIR"); outputDir != "" {
		c.OutputDir = outputDir
	}
	if batchSize := os.Getenv("KWDB_BATCH_SIZE"); batchSize != "" {
		if b, err := strconv.Atoi(batchSize); err == nil {
			c.BatchSize = b
		}
	}

	// 额外时间/标志配置
	if rd := os.Getenv("KWDB_RETRY_DELAY"); rd != "" {
		if d, err := time.ParseDuration(rd); err == nil {
			c.RetryDelay = d
		}
	}
	if ct := os.Getenv("KWDB_CONNECTION_TIMEOUT"); ct != "" {
		if d, err := time.ParseDuration(ct); err == nil {
			c.ConnectionTimeout = d
		}
	}
	if qt := os.Getenv("KWDB_QUERY_TIMEOUT"); qt != "" {
		if d, err := time.ParseDuration(qt); err == nil {
			c.QueryTimeout = d
		}
	}
	if v := os.Getenv("KWDB_VERBOSE"); v != "" {
		c.Verbose = strings.EqualFold(v, "true") || v == "1"
	}
	if dr := os.Getenv("KWDB_DRY_RUN"); dr != "" {
		c.DryRun = strings.EqualFold(dr, "true") || dr == "1"
	}

	// 日志配置
	if logLevel := os.Getenv("KWDB_LOG_LEVEL"); logLevel != "" {
		c.LogLevel = logLevel
	}
	if logFile := os.Getenv("KWDB_LOG_FILE"); logFile != "" {
		c.LogFile = logFile
	}
}

// LoadFromEnvironment 加载环境变量覆盖（测试期望的接口）
func (c *Config) LoadFromEnvironment() error {
	c.ApplyEnvironmentOverrides()
	c.syncToNested()
	return nil
}

// GetConnectionString 生成数据库连接字符串
func (c *Config) GetConnectionString() string {
	// 优先使用嵌套数据库配置
	host := c.Host
	port := c.Port
	db := c.DBName
	user := c.Username
	pass := c.Password
	ssl := c.SSLMode

	if host == "" {
		host = c.Database.Host
	}
	if port == 0 {
		port = c.Database.Port
	}
	if db == "" {
		if c.Database.Name != "" {
			db = c.Database.Name
		} else {
			db = c.Database.Database
		}
	}
	if user == "" {
		if c.Database.User != "" {
			user = c.Database.User
		} else {
			user = c.Database.Username
		}
	}
	if pass == "" {
		pass = c.Database.Password
	}
	if ssl == "" {
		ssl = c.Database.SSLMode
	}

	return fmt.Sprintf("host=%s port=%d dbname=%s user=%s password=%s sslmode=%s", host, port, db, user, pass, ssl)
}

// GetConnectionStringWithoutPassword 生成不包含密码的连接字符串（用于日志）
func (c *Config) GetConnectionStringWithoutPassword() string {
	host := c.Host
	port := c.Port
	db := c.DBName
	user := c.Username
	ssl := c.SSLMode

	if host == "" {
		host = c.Database.Host
	}
	if port == 0 {
		port = c.Database.Port
	}
	if db == "" {
		if c.Database.Name != "" {
			db = c.Database.Name
		} else {
			db = c.Database.Database
		}
	}
	if user == "" {
		if c.Database.User != "" {
			user = c.Database.User
		} else {
			user = c.Database.Username
		}
	}
	if ssl == "" {
		ssl = c.Database.SSLMode
	}
	return fmt.Sprintf("host=%s port=%d dbname=%s user=%s sslmode=%s", host, port, db, user, ssl)
}

// Validate 验证配置
func (c *Config) Validate() error {
	validator := NewConfigValidator()
	c.syncFromNested()
	return validator.ValidateConfig(c)
}

// GetTimeout 获取超时时间
func (c *Config) GetTimeout() (time.Duration, error) {
	if c.Timeout == "" {
		return 30 * time.Second, nil // 默认30秒
	}
	return time.ParseDuration(c.Timeout)
}

// GetConnectTimeout 获取连接超时时间
func (c *Config) GetConnectTimeout() (time.Duration, error) {
	if c.ConnectTimeout == "" {
		return 30 * time.Second, nil // 默认30秒
	}
	return time.ParseDuration(c.ConnectTimeout)
}

// GetMaxLifetime 获取连接最大生命周期
func (c *Config) GetMaxLifetime() (time.Duration, error) {
	if c.MaxLifetime == "" {
		return time.Hour, nil // 默认1小时
	}
	return time.ParseDuration(c.MaxLifetime)
}

// GetIdleTimeout 获取空闲超时时间
func (c *Config) GetIdleTimeout() (time.Duration, error) {
	if c.IdleTimeout == "" {
		return 15 * time.Minute, nil // 默认15分钟
	}
	return time.ParseDuration(c.IdleTimeout)
}

// Copy 创建配置的深拷贝
func (c *Config) Copy() *Config {
	newConfig := *c

	// 深拷贝map
	if c.DataTypeMapping != nil {
		newConfig.DataTypeMapping = make(map[string]string)
		for k, v := range c.DataTypeMapping {
			newConfig.DataTypeMapping[k] = v
		}
	}
	// 复制嵌套数据库配置
	newConfig.Database = c.Database

	return &newConfig
}

// Merge 合并另一个配置
func (c *Config) Merge(other *Config) *Config {
	if other == nil {
		return c
	}

	// 合并非零值
	if other.Host != "" {
		c.Host = other.Host
	}
	if other.Port != 0 {
		c.Port = other.Port
	}
	if other.DBName != "" {
		c.DBName = other.DBName
	}
	if other.Username != "" {
		c.Username = other.Username
	}
	if other.Password != "" {
		c.Password = other.Password
	}
	if other.SSLMode != "" {
		c.SSLMode = other.SSLMode
	}
	if other.InputFile != "" {
		c.InputFile = other.InputFile
	}
	if other.InputEncoding != "" {
		c.InputEncoding = other.InputEncoding
	}
	if other.OutputDir != "" {
		c.OutputDir = other.OutputDir
	}
	if other.BatchSize != 0 {
		c.BatchSize = other.BatchSize
	}
	if other.Timeout != "" {
		c.Timeout = other.Timeout
	}
	if other.MaxRetries != 0 {
		c.MaxRetries = other.MaxRetries
	}
	if other.RetryDelay != 0 {
		c.RetryDelay = other.RetryDelay
	}
	if other.ConnectionTimeout != 0 {
		c.ConnectionTimeout = other.ConnectionTimeout
	}
	if other.QueryTimeout != 0 {
		c.QueryTimeout = other.QueryTimeout
	}
	if other.Verbose {
		c.Verbose = other.Verbose
	}
	if other.DryRun {
		c.DryRun = other.DryRun
	}
	if other.ExecutionMode != "" {
		c.ExecutionMode = other.ExecutionMode
	}
	if other.TransactionMode != "" {
		c.TransactionMode = other.TransactionMode
	}
	if other.StatementsPerTransaction != 0 {
		c.StatementsPerTransaction = other.StatementsPerTransaction
	}
	if other.AutoRetry {
		c.AutoRetry = other.AutoRetry
	}
	// 错误处理配置
	if other.OnError != "" {
		c.OnError = other.OnError
	}
	if other.MaxErrors != 0 {
		c.MaxErrors = other.MaxErrors
	}
	if other.LogErrors {
		c.LogErrors = other.LogErrors
	}
	if other.LogLevel != "" {
		c.LogLevel = other.LogLevel
	}
	if other.LogFormat != "" {
		c.LogFormat = other.LogFormat
	}
	if other.LogFile != "" {
		c.LogFile = other.LogFile
	}

	// 合并转换扩展配置
	if other.MaxValuesPerInsert != 0 {
		c.MaxValuesPerInsert = other.MaxValuesPerInsert
	}

	// 合并并发与性能相关配置
	if other.EnableParallel {
		c.EnableParallel = other.EnableParallel
	}
	if other.WorkerCount != 0 {
		c.WorkerCount = other.WorkerCount
	}
	if other.ParallelBatchSize != 0 {
		c.ParallelBatchSize = other.ParallelBatchSize
	}
	if other.MemoryLimit != 0 {
		c.MemoryLimit = other.MemoryLimit
	}
	if other.EnableCompression {
		c.EnableCompression = other.EnableCompression
	}

	// 合并嵌套数据库配置
	if other.Database.Host != "" {
		c.Database.Host = other.Database.Host
	}
	if other.Database.Port != 0 {
		c.Database.Port = other.Database.Port
	}
	if other.Database.Name != "" || other.Database.Database != "" {
		if other.Database.Name != "" {
			c.Database.Name = other.Database.Name
		} else {
			c.Database.Database = other.Database.Database
		}
	}
	if other.Database.User != "" || other.Database.Username != "" {
		if other.Database.User != "" {
			c.Database.User = other.Database.User
		} else {
			c.Database.Username = other.Database.Username
		}
	}
	if other.Database.Password != "" {
		c.Database.Password = other.Database.Password
	}
	if other.Database.SSLMode != "" {
		c.Database.SSLMode = other.Database.SSLMode
	}

	// 合并数据类型映射
	if other.DataTypeMapping != nil {
		if c.DataTypeMapping == nil {
			c.DataTypeMapping = make(map[string]string)
		}
		for k, v := range other.DataTypeMapping {
			c.DataTypeMapping[k] = v
		}
	}
	return c
}

// GetSuggestions 获取配置建议
func (c *Config) GetSuggestions() []string {
	validator := NewConfigValidator()
	return validator.GetValidationSuggestions(c)
}

// IsProduction 判断是否为生产环境配置
func (c *Config) IsProduction() bool {
	return c.SSLMode != "disable" && c.LogLevel != "debug"
}

// IsDevelopment 判断是否为开发环境配置
func (c *Config) IsDevelopment() bool {
	return !c.IsProduction()
}

// GetWorkerCount 获取工作线程数
func (c *Config) GetWorkerCount() int {
	if c.WorkerCount <= 0 {
		return 4 // 默认4个工作线程
	}
	return c.WorkerCount
}

// GetMemoryLimitBytes 获取内存限制（字节）
func (c *Config) GetMemoryLimitBytes() int64 {
	if c.MemoryLimit <= 0 {
		return 512 * 1024 * 1024 // 默认512MB
	}
	return int64(c.MemoryLimit) * 1024 * 1024
}

// String 返回配置的字符串表示（隐藏敏感信息）
func (c *Config) String() string {
	// 打印顶层数据，Database 名称使用 DBName
	return fmt.Sprintf("Config{Host:%s, Port:%d, Database:%s, Username:%s, InputFile:%s, BatchSize:%d}",
		c.Host, c.Port, c.DBName, c.Username, c.InputFile, c.BatchSize)
}

// 同步：从嵌套 Database 到顶层字段
func (c *Config) syncFromNested() {
	// 仅在顶层字段缺失时进行填充，避免覆盖显式指定的值
	if c.Host == "" && c.Database.Host != "" {
		c.Host = c.Database.Host
	}
	if c.Port == 0 && c.Database.Port != 0 {
		c.Port = c.Database.Port
	}
	if c.DBName == "" {
		if c.Database.Name != "" {
			c.DBName = c.Database.Name
		} else if c.Database.Database != "" {
			c.DBName = c.Database.Database
		}
	}
	if c.Username == "" {
		if c.Database.User != "" {
			c.Username = c.Database.User
		} else if c.Database.Username != "" {
			c.Username = c.Database.Username
		}
	}
	if c.Password == "" && c.Database.Password != "" {
		c.Password = c.Database.Password
	}
	if c.SSLMode == "" && c.Database.SSLMode != "" {
		c.SSLMode = c.Database.SSLMode
	}

	// 从嵌套 Conversion 配置同步到顶层
	if c.DataTypeMapping == nil && c.Conversion.DataTypeMapping != nil {
		c.DataTypeMapping = c.Conversion.DataTypeMapping
	}
	if !c.ConvertAutoIncrement && c.Conversion.AutoIncrement {
		c.ConvertAutoIncrement = c.Conversion.AutoIncrement
	}
	if !c.ConvertEnumToVarchar && c.Conversion.EnumToVarchar {
		c.ConvertEnumToVarchar = c.Conversion.EnumToVarchar
	}
	if c.MaxValuesPerInsert == 0 && c.Conversion.MaxValuesPerInsert != 0 {
		c.MaxValuesPerInsert = c.Conversion.MaxValuesPerInsert
	}
}

// 同步：从顶层字段到嵌套 Database
func (c *Config) syncToNested() {
	if c.Host != "" {
		c.Database.Host = c.Host
	}
	if c.Port != 0 {
		c.Database.Port = c.Port
	}
	if c.DBName != "" {
		c.Database.Name = c.DBName
		c.Database.Database = c.DBName
	}
	if c.Username != "" {
		c.Database.User = c.Username
		c.Database.Username = c.Username
	}
	if c.Password != "" {
		c.Database.Password = c.Password
	}
	if c.SSLMode != "" {
		c.Database.SSLMode = c.SSLMode
	}

	// 从顶层同步到嵌套 Conversion 配置
	if c.DataTypeMapping != nil {
		c.Conversion.DataTypeMapping = c.DataTypeMapping
	}
	if c.ConvertAutoIncrement {
		c.Conversion.AutoIncrement = c.ConvertAutoIncrement
	}
	if c.ConvertEnumToVarchar {
		c.Conversion.EnumToVarchar = c.ConvertEnumToVarchar
	}
	if c.MaxValuesPerInsert != 0 {
		c.Conversion.MaxValuesPerInsert = c.MaxValuesPerInsert
	}
}
